package com.gin.no_gay_alliance.interceptor;

import android.util.Log;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 请求日志拦截器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/9 10:49
 **/
public class LoggingInterceptor implements Interceptor {
    private static final String TAG = LoggingInterceptor.class.getSimpleName();
    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("###,###.##");
    private static final List<String> SKIP_EXT = new ArrayList<>();

    static {
        SKIP_EXT.add(".gif");
        SKIP_EXT.add(".png");
        SKIP_EXT.add(".jpg");
    }

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        String url = request.url().toString();
        long startTime = System.nanoTime();
        boolean show = show(request);
        if (show) {
            String msg = String.format(Locale.CHINA,
                    "[%s] 发送请求: %s",
                    request.method(),
                    url);
            Log.d(TAG, msg);
//            Log.d(TAG, String.valueOf(request.headers()));
        }
        Response response = chain.proceed(request);

        long endTime = System.nanoTime();

        if (show) {
            String msg = String.format(Locale.CHINA,
                    "[%s] 响应请求: %s code: %d cost: %.1fms",
                    request.method(),
                    url,
                    response.code(),
                    (endTime - startTime) / 1e6d);
            String contentLength = response.header("Content-Length");
            if (contentLength != null) {
                msg += " length: " + DECIMAL_FORMAT.format(Long.parseLong(contentLength));
            }
            Log.d(TAG, msg);
        }
        // 重定向
        if (response.code() / 100 == 3) {
            Log.w(TAG, "重定向: " + response.header("location"));
        }

        return response;
    }

    /**
     * 判断是否需要打印日志
     *
     * @param request 请求
     * @return 是否打印日志
     */
    private static boolean show(Request request) {
        if ("post".equalsIgnoreCase(request.method())) {
            return true;
        }
        String url = request.url().toString();
        for (String s : SKIP_EXT) {
            if (url.contains(s)) {
                return false;
            }
        }
        return true;
    }
}
